package com.san.oa.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.san.base.service.DictService;
import com.san.common.utils.Constant;
import com.san.common.utils.DateUtils;
import com.san.common.utils.FileUtil;
import com.san.common.utils.PageUtils;
import com.san.common.utils.StringUtils;
import com.san.oa.dao.NotifyDao;
import com.san.oa.dao.NotifyRecordDao;
import com.san.oa.domain.NotifyDO;
import com.san.oa.domain.NotifyDTO;
import com.san.oa.domain.NotifyRecordDO;
import com.san.oa.service.NotifyService;
import com.san.oa.vo.NotifyVO;
import com.san.system.dao.UserDao;
import com.san.system.domain.UserDO;
import com.san.system.service.SessionService;

@Service
public class NotifyServiceImpl implements NotifyService {

	@Value("${san.uploadPath}")
	private String uploadPath;

	@Autowired
	private NotifyDao notifyDao;
	@Autowired
	private NotifyRecordDao recordDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private DictService dictService;
	@Autowired
	private SessionService sessionService;
	@Autowired
	private SimpMessagingTemplate template;

	@Override
	public Object getById(Long id) {
		return notifyDao.getById(id);
	}

	@Override
	public List<NotifyDO> list(Map<String, Object> map) {
		List<NotifyDO> notifys = notifyDao.list(map);
		for (NotifyDO notifyDO : notifys) {
			notifyDO.setTypeDesc(dictService.getName("oa_notify_type", notifyDO.getType()+""));
		}
		return notifys;
	}

	@Override
	public int count(Map<String, Object> map) {
		return notifyDao.count(map);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public int save(Object obj) {
		NotifyVO notify = (NotifyVO) obj;
		notify.setUpdateDate(new Date());

		MultipartFile file = notify.getFile();
		if (null != file && !file.isEmpty()) {
			// 上传文件名称
			String oldFileName = file.getOriginalFilename();
			StringBuffer path = new StringBuffer(this.buildPath(Constant.NOTIFY_PATH_USER));

			// 新文件名
			String newFileName = UUID.randomUUID().toString() + "_" + oldFileName;
			notify.setFilePath(path + newFileName);

			try {
				// 写文件
				FileUtil.saveFileFromInputStream(file.getInputStream(), path.toString(), newFileName);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		int r = notifyDao.save(notify);

		// 保存到接受者列表中
		Long[] userIds = notify.getUserIds();
		Long notifyId = notify.getId();
		List<NotifyRecordDO> records = new ArrayList<>();
		for (Long userId : userIds) {
			NotifyRecordDO record = new NotifyRecordDO();
			record.setNotifyId(notifyId);
			record.setUserId(userId);
			record.setIsRead(0);
			records.add(record);
		}
		recordDao.batchSave(records);
		// 给在线用户发送通知
		ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
				new LinkedBlockingDeque<>());
		executor.execute(new Runnable() {
			@Override
			public void run() {
				for (UserDO userDO : sessionService.listOnlineUser()) {
					for (Long userId : userIds) {
						if (userId.equals(userDO.getUserId())) {
							template.convertAndSendToUser(userDO.toString(), "/queue/notifications",
									"新消息：" + notify.getTitle());
						}
					}
				}
			}
		});
		executor.shutdown();
		return r;
	}

	@Override
	public int doEdit(Object obj) {
		NotifyVO notify = (NotifyVO) obj;
		MultipartFile file = notify.getFile();
		if (null != file && !file.isEmpty()) {
			// 上传文件名称
			String oldFileName = file.getOriginalFilename();
			StringBuffer path = new StringBuffer(this.buildPath(Constant.NOTIFY_PATH_USER));

			// 新文件名
			String newFileName = UUID.randomUUID().toString() + "_" + oldFileName;
			notify.setFilePath(path + newFileName);

			try {
				// 写文件
				FileUtil.saveFileFromInputStream(file.getInputStream(), path.toString(), newFileName);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			notify.setFilePath(null);
		}

		return notifyDao.doEdit(notify);
	}

	@Transactional
	@Override
	public int remove(Long id) {
		recordDao.removeByNotifbyId(id);
		return notifyDao.remove(id);
	}

	@Transactional
	@Override
	public int batchRemove(Long[] ids) {
		recordDao.batchRemoveByNotifbyId(ids);
		return notifyDao.batchRemove(ids);
	}

	@Override
	public PageUtils selfList(Map<String, Object> map) {
		List<NotifyDTO> rows = notifyDao.listDTO(map);
		for (NotifyDTO notifyDTO : rows) {
			notifyDTO.setBefore(DateUtils.getTimeBefore(
					null == notifyDTO.getUpdateDate() ? notifyDTO.getCreateDate() : notifyDTO.getUpdateDate()));
			UserDO userDO = (UserDO)userDao.getById(notifyDTO.getCreateUserId());
			notifyDTO.setSender(userDO.getName());
		}
		PageUtils page = new PageUtils(rows, notifyDao.countDTO(map));
		return page;
	}

	@Override
	public String buildPath(String childFolder) {

		StringBuffer path = new StringBuffer(uploadPath);
		if (!uploadPath.endsWith(File.separator)) {
			path.append(File.separator);
		}
		path.append("通知公告");// 增加通知公告文件夹
		path.append(File.separator);
		if (StringUtils.isEmpty(childFolder)) {
			path.append(childFolder);// 增加文件夹
			path.append(File.separator);
		}

		return path.toString();
	}

}
